package com.nakamachizu.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.RandomStringUtils;
import org.slim3.util.StringUtil;

public class TokenCheck {
    
    private static final String TOKEN_CHECK_SESSION_KEY = "tokenCheckSessionKey";

    public static boolean validate(HttpServletRequest request){
        boolean result = false;
        HttpSession session = request.getSession();
        if(session != null){
            String sToken = (String)session.getAttribute(TOKEN_CHECK_SESSION_KEY);
            String rToken = (String)request.getAttribute(TOKEN_CHECK_SESSION_KEY);
            if(!StringUtil.isEmpty(sToken) && !StringUtil.isEmpty(rToken)){
                if(sToken.equals(rToken)){
                    session.removeAttribute(TOKEN_CHECK_SESSION_KEY);
                    result = true;
                }
            }
        }
        return result;
    }
    
    public static void saveToken(HttpServletRequest request){
        String token = RandomStringUtils.randomAlphanumeric(32);
        HttpSession session = request.getSession();
        if(session != null){
            session.setAttribute(TOKEN_CHECK_SESSION_KEY, token);
            request.setAttribute(TOKEN_CHECK_SESSION_KEY, token);
        }
    }

    /**
     * @return the tOKEN_CHECK_SESSION_KEY
     */
    public static String TOKEN_CHECK_SESSION_KEY() {
        return TOKEN_CHECK_SESSION_KEY;
    }
}
